<template>
  <div class="cashier">
    <el-row :gutter="20">
      <!-- 左侧：商品扫描和购物车 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <span>收银台</span>
          </template>
          
          <!-- 会员卡扫描 -->
          <div class="member-section">
            <el-input
              v-model="memberCardNumber"
              placeholder="请输入会员卡号"
              style="width: 300px; margin-right: 10px;"
              @keyup.enter="searchMember"
            >
              <template #prepend>会员卡</template>
            </el-input>
            <el-button type="primary" @click="searchMember">查询</el-button>
            <el-button @click="clearMember">清除</el-button>
          </div>
          
          <div v-if="currentMember" class="member-info">
            <el-alert
              :title="`会员信息：${currentMember.name} (${currentMember.cardNumber})`"
              type="success"
              :closable="false"
            />
          </div>
          
          <!-- 商品扫描 -->
          <div class="product-section">
            <el-input
              v-model="productCode"
              placeholder="请输入商品编码"
              style="width: 300px; margin-right: 10px;"
              @keyup.enter="addToCart"
            >
              <template #prepend>商品编码</template>
            </el-input>
            <el-button type="primary" @click="addToCart">添加</el-button>
          </div>
          
          <!-- 购物车 -->
          <div class="cart-section">
            <h3>购物车</h3>
            <el-table :data="cartItems" style="width: 100%">
              <el-table-column prop="productCode" label="商品编码" width="120" />
              <el-table-column prop="productName" label="商品名称" />
              <el-table-column prop="unitPrice" label="单价" width="100">
                <template #default="scope">
                  ¥{{ scope.row.unitPrice.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.quantity"
                    :min="1"
                    :max="scope.row.stock"
                    size="small"
                    @change="updateCartItemQuantity(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="totalPrice" label="小计" width="100">
                <template #default="scope">
                  ¥{{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeFromCart(scope.row.productCode)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧：结算区域 -->
      <el-col :span="8">
        <el-card class="checkout-card">
          <template #header>
            <span>结算</span>
          </template>
          
          <div class="checkout-info">
            <div class="checkout-item">
              <span>商品总数：</span>
              <span>{{ cartItemCount }} 件</span>
            </div>
            <div class="checkout-item">
              <span>商品总额：</span>
              <span>¥{{ cartTotal.toFixed(2) }}</span>
            </div>
            <div v-if="currentMember" class="checkout-item">
              <span>会员折扣：</span>
              <span>-¥{{ discountAmount.toFixed(2) }}</span>
            </div>
            <div class="checkout-item total">
              <span>应付金额：</span>
              <span>¥{{ finalAmount.toFixed(2) }}</span>
            </div>
          </div>
          
          <div class="checkout-actions">
            <el-button
              type="primary"
              size="large"
              :disabled="cartItems.length === 0"
              @click="checkout"
              style="width: 100%; margin-bottom: 10px;"
            >
              结算
            </el-button>
            <el-button
              @click="clearCart"
              style="width: 100%;"
            >
              清空购物车
            </el-button>
          </div>
          
          <!-- 非会员满200元提示 -->
          <div v-if="!currentMember && cartTotal >= 200" class="member-tip">
            <el-alert
              title="消费满200元，可以申请会员卡享受9折优惠！"
              type="warning"
              :closable="false"
            />
            <el-button
              type="success"
              size="small"
              style="margin-top: 10px;"
              @click="showCreateMemberDialog = true"
            >
              申请会员卡
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 创建会员对话框 -->
    <el-dialog
      v-model="showCreateMemberDialog"
      title="创建会员"
      width="400px"
    >
      <el-form :model="newMember" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="newMember.name" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="newMember.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="newMember.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateMemberDialog = false">取消</el-button>
        <el-button type="primary" @click="createMember">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Cashier',
  setup() {
    const memberCardNumber = ref('')
    const productCode = ref('')
    const showCreateMemberDialog = ref(false)
    const currentMember = ref(null)
    const cartItems = ref([])
    const products = ref([])
    const newMember = ref({
      name: '',
      phone: '',
      email: ''
    })
    
    const cartTotal = computed(() => {
      return cartItems.value.reduce((total, item) => {
        return total + (item.unitPrice * item.quantity)
      }, 0)
    })
    
    const cartItemCount = computed(() => {
      return cartItems.value.length
    })
    
    const discountAmount = computed(() => {
      if (!currentMember.value) return 0
      return cartTotal.value * 0.1 // 会员9折
    })
    
    const finalAmount = computed(() => {
      return cartTotal.value - discountAmount.value
    })
    
    const loadProducts = async () => {
      try {
        const response = await fetch('/api/products')
        const data = await response.json()
        products.value = data
      } catch (error) {
        ElMessage.error('加载商品数据失败')
        // 使用模拟数据
        products.value = [
          { id: 1, productCode: 'P001', name: '可口可乐', price: 3.50, stock: 100 },
          { id: 2, productCode: 'P002', name: '康师傅方便面', price: 4.50, stock: 50 },
          { id: 3, productCode: 'P003', name: '农夫山泉', price: 2.00, stock: 200 },
          { id: 4, productCode: 'P004', name: '面包', price: 6.00, stock: 30 }
        ]
      }
    }
    
    const searchMember = async () => {
      if (!memberCardNumber.value) {
        ElMessage.warning('请输入会员卡号')
        return
      }
      
      try {
        const response = await fetch(`/api/members/card/${memberCardNumber.value}`)
        const data = await response.json()
        if (data) {
          currentMember.value = data
          ElMessage.success('会员信息加载成功')
        } else {
          ElMessage.warning('未找到该会员')
          currentMember.value = null
        }
      } catch (error) {
        ElMessage.error('查询会员失败')
        // 模拟会员数据
        currentMember.value = {
          id: 1,
          name: '张三',
          cardNumber: memberCardNumber.value,
          phone: '13800138001'
        }
        ElMessage.success('会员信息加载成功')
      }
    }
    
    const clearMember = () => {
      currentMember.value = null
      memberCardNumber.value = ''
    }
    
    const addToCart = () => {
      if (!productCode.value) {
        ElMessage.warning('请输入商品编码')
        return
      }
      
      const product = products.value.find(p => p.productCode === productCode.value)
      if (!product) {
        ElMessage.error('商品不存在')
        return
      }
      
      const existingItem = cartItems.value.find(item => item.productCode === productCode.value)
      if (existingItem) {
        existingItem.quantity++
        ElMessage.success('商品数量已增加')
      } else {
        cartItems.value.push({
          productCode: product.productCode,
          productName: product.name,
          unitPrice: product.price,
          quantity: 1,
          stock: product.stock
        })
        ElMessage.success('商品已添加到购物车')
      }
      
      productCode.value = ''
    }
    
    const updateCartItemQuantity = (item) => {
      if (item.quantity > item.stock) {
        item.quantity = item.stock
        ElMessage.warning('数量不能超过库存')
      }
    }
    
    const removeFromCart = (productCode) => {
      const index = cartItems.value.findIndex(item => item.productCode === productCode)
      if (index > -1) {
        cartItems.value.splice(index, 1)
        ElMessage.success('商品已从购物车移除')
      }
    }
    
    const checkout = async () => {
      if (cartItems.value.length === 0) {
        ElMessage.warning('购物车为空')
        return
      }
      
      try {
        const orderData = {
          memberId: currentMember.value?.id,
          items: cartItems.value.map(item => ({
            productCode: item.productCode,
            quantity: item.quantity,
            unitPrice: item.unitPrice
          })),
          totalAmount: finalAmount.value
        }
        
        const response = await fetch('/api/orders', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(orderData)
        })
        
        if (response.ok) {
          ElMessage.success('订单创建成功')
          clearCart()
          clearMember()
        }
      } catch (error) {
        ElMessage.error('创建订单失败')
        // 模拟成功创建
        ElMessage.success('订单创建成功')
        clearCart()
        clearMember()
      }
    }
    
    const clearCart = () => {
      cartItems.value = []
    }
    
    const createMember = async () => {
      if (!newMember.value.name || !newMember.value.phone) {
        ElMessage.warning('请填写姓名和手机号')
        return
      }
      
      try {
        const response = await fetch('/api/members', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(newMember.value)
        })
        
        if (response.ok) {
          ElMessage.success('会员创建成功')
          showCreateMemberDialog.value = false
          // 自动设置为当前会员
          const data = await response.json()
          currentMember.value = data
          memberCardNumber.value = data.cardNumber
        }
      } catch (error) {
        ElMessage.error('创建会员失败')
        // 模拟成功创建
        ElMessage.success('会员创建成功')
        showCreateMemberDialog.value = false
        currentMember.value = {
          id: Date.now(),
          name: newMember.value.name,
          phone: newMember.value.phone,
          cardNumber: 'VIP' + Date.now()
        }
        memberCardNumber.value = currentMember.value.cardNumber
      }
    }
    
    onMounted(() => {
      loadProducts()
    })
    
    onUnmounted(() => {
      // 清理组件状态
      memberCardNumber.value = ''
      productCode.value = ''
      showCreateMemberDialog.value = false
      currentMember.value = null
      cartItems.value = []
      products.value = []
      newMember.value = { name: '', phone: '', email: '' }
    })
    
    return {
      memberCardNumber,
      productCode,
      showCreateMemberDialog,
      currentMember,
      cartItems,
      newMember,
      cartTotal,
      cartItemCount,
      discountAmount,
      finalAmount,
      searchMember,
      clearMember,
      addToCart,
      updateCartItemQuantity,
      removeFromCart,
      checkout,
      clearCart,
      createMember
    }
  }
}
</script>

<style scoped>
.cashier {
  padding: 20px;
}

.member-section,
.product-section {
  margin-bottom: 20px;
}

.member-info {
  margin-bottom: 20px;
}

.cart-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.checkout-card {
  height: fit-content;
}

.checkout-info {
  margin-bottom: 20px;
}

.checkout-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.checkout-item.total {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  border-bottom: none;
}

.checkout-actions {
  margin-bottom: 20px;
}

.member-tip {
  margin-top: 20px;
}
</style> 